function varargout = BAT(varargin)
% BAT MATLAB code for BAT.fig
%      BAT, by itself, creates a new BAT or raises the existing
%      singleton*.
%
%      H = BAT returns the handle to a new BAT or the handle to
%      the existing singleton*.
%
%      BAT('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in BAT.M with the given input arguments.
%
%      BAT('Property','Value',...) creates a new BAT or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before BAT_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to BAT_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help BAT

% Last Modified by GUIDE v2.5 18-Oct-2011 15:21:54

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @BAT_OpeningFcn, ...
                   'gui_OutputFcn',  @BAT_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before BAT is made visible.
function BAT_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to BAT (see VARARGIN)

% Choose default command line output for BAT
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes BAT wait for user response (see UIRESUME)
uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = BAT_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes when selected object is changed in BATpanel.
function BATpanel_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in BATpanel 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)

  % First, confirm availability of and set base_dir
    [status, ~] = dos('@ping -n 1 ecylcyfsvrxfile | find "Lost = 0" > nul'); % Check that output drive is accessible
    if ~status
        base_dir = '\\ecylcyfsvrxfile\eap\SHARED Files\MWDataMgmt\VSS_Mirror\rt\Telnet';        
    else
        report_state(['Sorry, I can''t find the output drive!  ' ...
                      'Please independently check access to \\ecylcyfsvrxfile\eap.  ' ...
                      'If you can read and write to it, try this program again; ' ...
                      'if you still get this error, email dgol461@ecy.wa.gov.'])
        return
    end

  % Get the selected button
    selection = get(eventdata.NewValue, 'Tag');
  % Need to change selection if it begin w/ an r
    if strcmp(selection(1), 'r')
        selection = '37IDOAP';
    end

  % If applicable, get the sensor data
    if ~strcmp(selection, 'Winkler')
%        origBaseDir = base_dir;
        cmd = ['"' base_dir '\windist\autoTelnetDriver.exe" HQ' selection ' &'];
%        working = msgbox('Getting data...');
%        set(findobj(working, 'String', 'OK'), 'Enable', 'off')
        [status, result] = dos(cmd);
        start = now;
%         if ~status
%             msg = ['Data downloaded successfully to ' char(10) base_dir...
%                    '\Output\HQ\' selection char(10) 'Click OK to continue.'];
%        else
        if status
%            clear working
            report_state(['Attempt to get data failed.' char(10)...
                   sprintf('The call to autoTelnetDriver returned status code %d', status)...
                   char(10) 'and result' char(10) result])
%             set(findobj(working, 'String', 'Getting data...'), 'String', msg)
%             set(findobj(working, 'String', 'OK'), 'Enable', 'on')
            return
        end 
%        uiwait(working{1})
    end
  % While that's going on:
  % All options require a bath date and a link date
    [btmp, ~] = DOCTgetdate(now, 'Please choose bath datetime');
    if isempty(btmp)
        bathDate = '';
    else
        bathDate = datestr(btmp, 'mm/dd/yyyy HH:MM:SS');
    end
    
    handles.output = struct('bathDate', bathDate,...
                            'tiedTo', '',...
                            'sensorID', '',...
                            'Winkler', []);
    if ~strcmp(selection, 'Winkler')
        WinklerDir = uigetdir('', 'Please choose the associated Winkler directory');
        filelist = dir(WinklerDir);
        choices = {filelist(~[filelist(:).isdir]).name};
        tiedToFig = figure('MenuBar', 'none', 'Name', 'Tied to choices',...
                           'NumberTitle', 'off', 'Visible', 'off');
        tiedToList = uicontrol('Parent', tiedToFig, 'Style', 'popupmenu',...
                               'String', choices, 'Callback', @listcb);
        makeSnug(tiedToFig)
        set(tiedToFig, 'Visible', 'on')
        uiwait
        handles.output.tiedTo = choices{get(tiedToList, 'Value')};
        close(tiedToFig)
        if strcmp(selection(1), 'S')
            handles.output.sensorID = inputdlg('Sensor ID', 'Please enter a sensor ID.', 1, {''},...
                                               struct('Resize', 'on', 'WindowStyle', 'normal'));
        end        
      % Wait 'til 30 seconds has elapsed from start
        while (now-start < 1/2880), end
      % Assume data has been obtained
%        close(working)
        files = dir([base_dir '\Output\HQ\' selection]);
        latest = files([files(:).datenum] == max([files(:).datenum]));
        fid = fopen([base_dir '\Output\HQ\' selection '\' latest.name], 'at');
    %     while (fid == -1) && (now-start < 1/576) 
    %         fid = fopen([origBaseDir '\Output\HQ\' selection '\' latest.name], 'at');
    %     end
        if fid == -1 % if we went five minutes w/out being able to open the file
            report_state(['Sorry, acquisition of the sensor data has failed.' char(10)...
                          'Please check network connectivity and try again.'])
            return
        end
        fprintf(fid, 'Bath date: %s\n', handles.output.bathDate);
        fprintf(fid, 'Tied to: %s\n', handles.output.tiedTo);
        if strcmp(selection(1), 'S')
            fprintf(fid, 'Sensor ID: %s\n', handles.output.sensorID{1});
        end        
        fclose(fid);
    else
        handles.output.Winkler = Winkler1;
      % Ask where to save the results
        suggestedFilename = ['BD' datestr(bathDate,'mm-dd-yyyy')];
        [fn, pn] = uiputfile('*.txt', 'Suggested output file name',...
                             suggestedFilename);
        if ~isempty(fn)
            if isempty(pn), pn = '.\'; end
            fid = fopen(fullfile(pn,fn), 'wt');
            if fid ~= -1
                if ~isempty(handles.output.Winkler)
                    fprintf(fid, 'Winkler Data:\n');
                    fprintf(fid, [sprintf('%s\t', handles.output.Winkler{:}) '\n']);
                end
            end
        end
    end
    
  % Clear selection in case user wants to select same again
    set(handles.BATpanel, 'SelectedObject', [])
    
%    handles.output = struct('bathdate', bathDate, 'data', data);
    
  % Update handles structure
    guidata(hObject, handles);
    
    uiresume
    
function choice = listcb(varargin)
    uiresume
        